package com.example.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class HorseRace {
    private static List<String> results= Collections.synchronizedList(new ArrayList<>());
    private static CountDownLatch countDownLatch=new CountDownLatch(1);
    private static CyclicBarrier finishBarrier=new CyclicBarrier(10, new Runnable() {
        @Override
        public void run() {
            System.out.println("rose is finished! Announcing results:");
            for(String result:results){
                System.out.println(result);
            }
        }
    });

    public static void main(String[] args) {
        for(int i=1;i<=10;i++){
            new Thread(new Horse("horse-"+i)).start();
        }
        System.out.println("all horses ready, Race starts now");
        countDownLatch.countDown();
    }

    private static class Horse implements Runnable {
        private String name;
        public Horse(String name) {
            this.name=name;
        }

        @Override
        public void run() {
            try {
                countDownLatch.await();
                long raceTime= (long) (Math.random()*10000);
                Thread.sleep(raceTime);
                results.add(name+"finish in"+raceTime+"ms");
                finishBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }
}
